package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        try{
            System.out.println("正在连接服务器");
            socket = new Socket("localhost",6666);
            System.out.println("连接服务器成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            //启动一个新线程，用于接受服务端发来的消息
            ServerHandler serverHandler = new ServerHandler();
            Thread t = new Thread(serverHandler);
            t.start();

            //以下代码位于主线程中，用于像服务端发送消息
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(ow);
            PrintWriter pw = new PrintWriter(bw,true);
            Scanner scan = new Scanner(System.in);

            while (true){
                System.out.println("请输入昵称：");
                String nickName = scan.nextLine();
                if (nickName.trim().isEmpty()){
                    System.out.println("昵称不能为空，请重新输入");
                }else  {
                    pw.println(nickName);
                    break;
                }
            }

            while(true){
                System.out.println("请输入要发送的消息：");
                String msg = scan.nextLine();
                if ("exit".equalsIgnoreCase(msg)){
                    break;
                }
                pw.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    /**
     * 该线程用于接受服务端发来的消息
     */
    private class ServerHandler implements Runnable{
        public void run(){
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String msg;
                while((msg = br.readLine()) != null){
                    System.out.println(msg);
                }
            } catch (IOException e){
            }
        }
    }
}
